from django.db.models.signals import post_save
from django.dispatch import receiver
from django.db import transaction
from orders.models import Order, Reviews
from decimal import Decimal
class CreditRule:
    """信用分计算规则"""
    # 加分项
    GOOD_REVIEW = Decimal('0.3')  # 获得好评(4-5星)
    FAST_SHIPPING = Decimal('0.2')  # 24小时内发货
    ONTIME_COMPLETE = Decimal('0.1')  # 按时完成交易

    # 减分项（改为Decimal类型）
    BAD_REVIEW = Decimal('-0.5')  # 差评(1-2星)
    CANCEL_ORDER = Decimal('-0.3')  # 无故取消订单
    LATE_SHIPPING = Decimal('-0.4')  # 超时发货(>3天)
    REPORT_PENALTY = Decimal('-1.0')  # 被举报核实
    FAKE_PRODUCT = Decimal('-2.0')  # 售假


@receiver(post_save, sender=Reviews)
def update_credit_after_review(sender, instance, created, **kwargs):
    """评价提交后的信用分更新"""
    if not created:
        return
        
    with transaction.atomic():
        seller = instance.order.seller
        if instance.rating >= 4:  # 4-5星好评
            seller.credit_score = min(
                10.0, 
                seller.credit_score + CreditRule.GOOD_REVIEW
            )
        elif instance.rating <= 2:  # 1-2星差评
            seller.credit_score = max(
                1.0,
                seller.credit_score + CreditRule.BAD_REVIEW
            )
        seller.save(update_fields=['credit_score'])

@receiver(post_save, sender=Order)
def update_credit_after_order(sender, instance, created, **kwargs):
    """订单状态变更时的信用分更新"""
    if created:
        return
        
    # 从数据库获取订单原始状态
    try:
        original_order = Order.objects.get(id=instance.id)
        if original_order.status == instance.status:
            return
    except Order.DoesNotExist:
        return
        
    with transaction.atomic():
        seller = instance.seller
        seller.credit_score = max(1.0, min(10.0, seller.credit_score))
        # 发货时效检查
        if instance.status == 2:  # 待收货(已发货)
            ship_time = (instance.deliver_time - instance.payment_time).total_seconds()
            if ship_time < 24*3600:  # 24小时内发货
                seller.credit_score = min(
                    10.0,
                    seller.credit_score + CreditRule.FAST_SHIPPING
                )
            elif ship_time > 3*24*3600:  # 超过3天发货
                seller.credit_score = max(
                    1.0,
                    seller.credit_score + CreditRule.LATE_SHIPPING
                )
            seller.save(update_fields=['credit_score'])